const request = require("request");
const config = require("../../config/env.config");
const crypto = require("crypto");
const redis = require("redis");
const sha1 = require("sha1");
const redisClient = redis.createClient();
const appid = config.appID;
const appsecret = config.appsecret;

/*---------获取access_token------*/
exports.getAccess_token = function(req,res,next){
    let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`;
    redisClient.get("access_token", function(err, data){
        if(data){
            console.log(`redis服务器存在access_token, 且有效!`);
            req.access_token = data;
            next();
        }else{
            console.log(`redis服务器不存在access_token, 或已过期`);
            request(url, function(err, httpResponse,body){
                console.log(err);
                console.log(body);
                let result = JSON.parse(body);
                let access_token = result.access_token;
                redisClient.set("access_token", access_token);
                redisClient.expire("access_token", result.expires_in - 100);

                req.access_token = access_token;
                next();
            });
        };
    });
};

/*-----------获取ticket---------*/
exports.getTicket = function(req,res,next){
    let access_token = req.access_token;
    let url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;

    redisClient.get("ticket", function(err, data){
        if(data){
            console.log("redis服务器中存在ticket, 且有效!");
            req.ticket = data;
            next();
        }else{
            console.log("redis服务器中不存在ticket, 且已过期!");
            request(url, function(err, httpResponse, body){
                console.log(err);
                console.log(body);
                let result = JSON.parse(body);

                redisClient.set("ticket", result.ticket);
                redisClient.expire("ticket", result.expires_in - 100);

                req.ticket = result.ticket;
                next();
            });
        }
    })

};


/*----------生成签名----------*/
exports.getSignature = function(req,res,next){
    let ticket = req.ticket;
    let timestamp = parseInt(new Date().getTime() / 1000);
    let url = req.query.url;
    let noncestr = crypto.randomBytes(8).toString('hex');
    console.log("ticket: ", ticket);
    console.log("timestamp: ", timestamp);
    console.log("url: ", url);
    console.log("noncestr: ", noncestr);

    let str = [`jsapi_ticket=${ticket}`, `noncestr=${noncestr}`, `timestamp=${timestamp}`, `url=${url}`].sort().join("&");

    console.log(str);
    let signature  = sha1(str);
    console.log("signature: ")
    console.log(signature);

    req.signature = signature;
    req.appId = appid;
    req.timestamp = timestamp;
    req.nonceStr = noncestr;
    next();
};